package com.lunwen.dao;

import com.lunwen.domain.User;
import com.lunwen.utils.JdbcTemplate;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserDao {

    private static JdbcTemplate jdbcTemplate;

    public UserDao(){
        jdbcTemplate = JdbcTemplate.getJdbcTemplate();
    }

    //查找所有管理员(暂时不用)
    public List<User> query(Map<String,Object> condition) {
        StringBuffer sql = new StringBuffer("select * from user where 1=1");
        List<Object> objects = new ArrayList<Object>();
        condition.forEach((key,value)->{
            sql.append(" and "+key+"=?");
            objects.add(value);
        });
        System.out.println(sql);
        List<User> query = null;
        try {
            query = jdbcTemplate.query(sql.toString(), User.class,objects.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    //通过名字查找管理员(用作登录)
    public List<User> findByName(String name) {
        String sql = "select * from user where name=?";
        List<User> query = null;
        try {
            query = jdbcTemplate.query(sql, User.class,name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    //更新密码
    public int updatePassword(String oldPassword, String newPassword){
        String sql = "update user set password=? where password=?";
        try {
            return jdbcTemplate.modify(sql,
                    newPassword,
                    oldPassword);
        } catch (SQLException e) {
            return -1;
        }
    }

//    public static void main(String[] args) {
//        //System.out.println(findByName("root").get(0).getPassword());
//        System.out.println(updatePassword("abc123", "123abc"));
//    }
}
